package mands.utils.weather;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * Weather.java
 * 
 * @author Maze
 * 
 *         Utility class to gather weather information of a given zip code or
 *         city from http://www.google.com/ig/api?weather=
 */
public class Weather {

	private static CurrentConditions currentConditions;
	private static WeatherForecast[] weatherForecasts;

	/**
	 * Gathers and returns the raw xml string of the city or zip code.
	 * 
	 * @param cityOrZip
	 *            City or zip code for weather information.
	 * @return String containing the raw xml weather information.
	 */
	public static String getRawWeatherInformation(String cityOrZip) {
		String rawWeatherInformation = null;

		try {
			String queryString = "http://www.google.com/ig/api?weather="
					+ cityOrZip;
			queryString.replace(" ", "%20");

			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(queryString);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			rawWeatherInformation = EntityUtils.toString(httpEntity);

		} catch (Exception e) {
			Log.e("getXML", e.toString());
		}

		return rawWeatherInformation;
	}

	/**
	 * Update the current weather information based on the city or zip code.
	 * 
	 * @param cityOrZip
	 *            The city or zip code to get weather for.
	 */
	public static void updateCurrentInformation(String cityOrZip) {
		String rawWeatherInformation = getRawWeatherInformation(cityOrZip);
		currentConditions = WeatherParser
				.parseCurrentConditions(rawWeatherInformation);
		weatherForecasts = WeatherParser
				.parseWeatherForecasts(rawWeatherInformation);
	}

	// Get Methods
	public static CurrentConditions getCurrentConditions() {
		return currentConditions;
	}

	public static WeatherForecast[] getWeatherForecasts() {
		return weatherForecasts;
	}
}
